<template>
  <div class="device-list-page">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total">
              <el-icon :size="40"><Box /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-label">设备总数</div>
              <div class="stat-value">{{ stats.total }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon online">
              <el-icon :size="40"><Check /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-label">在线设备</div>
              <div class="stat-value">{{ stats.online }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon offline">
              <el-icon :size="40"><Close /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-label">离线设备</div>
              <div class="stat-value">{{ stats.offline }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-icon rate">
              <el-icon :size="40"><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-label">在线率</div>
              <div class="stat-value">{{ stats.onlineRate }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 设备列表 -->
    <el-card shadow="never" class="device-list-card">
      <!-- 操作栏 -->
      <div class="toolbar">
        <div class="toolbar-left">
          <el-input
            v-model="searchText"
            placeholder="搜索设备名称或ID"
            :prefix-icon="Search"
            style="width: 300px"
            clearable
            @input="handleSearch"
          />
          <el-select
            v-model="statusFilter"
            placeholder="状态筛选"
            style="width: 150px"
            @change="handleFilter"
          >
            <el-option label="全部" value="all" />
            <el-option label="在线" value="online" />
            <el-option label="离线" value="offline" />
          </el-select>
        </div>
        <div class="toolbar-right">
          <el-button type="primary" :icon="Plus" @click="handleAdd">
            添加设备
          </el-button>
          <el-button :icon="Refresh" @click="fetchData">刷新</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="deviceList"
        style="width: 100%"
        stripe
      >
        <el-table-column prop="deviceId" label="设备ID" width="200" />
        <el-table-column prop="deviceName" label="设备名称" width="200" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'online' ? 'success' : 'info'">
              {{ row.status === 'online' ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="最后上线时间" width="200">
          <template #default="{ row }">
            {{ formatTime(row.lastOnlineTime) }}
          </template>
        </el-table-column>
        <el-table-column label="最后心跳时间" width="200">
          <template #default="{ row }">
            {{ formatTime(row.lastHeartbeatTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="ipAddress" label="IP地址" width="150" />
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">
              查看
            </el-button>
            <el-button link type="primary" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="设备ID" prop="deviceId">
          <el-input
            v-model="form.deviceId"
            :disabled="isEdit"
            placeholder="请输入设备ID"
          />
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="IP地址" prop="ipAddress">
          <el-input v-model="form.ipAddress" placeholder="请输入IP地址（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Refresh } from '@element-plus/icons-vue'
import { getDeviceList, getDeviceStats, createDevice, updateDevice, deleteDevice } from '@/api/device'
import { formatTime } from '@/utils/format'

const router = useRouter()

// 统计数据
const stats = ref({
  total: 0,
  online: 0,
  offline: 0,
  onlineRate: 0
})

// 列表数据
const loading = ref(false)
const deviceList = ref([])
const searchText = ref('')
const statusFilter = ref('all')

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const formRef = ref(null)
const form = reactive({
  deviceId: '',
  deviceName: '',
  ipAddress: ''
})

const rules = {
  deviceId: [
    { required: true, message: '请输入设备ID', trigger: 'blur' }
  ],
  deviceName: [
    { required: true, message: '请输入设备名称', trigger: 'blur' }
  ]
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const res = await getDeviceStats()
    stats.value = res.data
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取列表数据
const fetchList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize
    }
    
    if (statusFilter.value !== 'all') {
      params.status = statusFilter.value
    }
    
    if (searchText.value) {
      params.search = searchText.value
    }
    
    const res = await getDeviceList(params)
    deviceList.value = res.data.list
    pagination.total = res.data.total
  } catch (error) {
    console.error('获取设备列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取所有数据
const fetchData = () => {
  fetchStats()
  fetchList()
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchList()
}

// 筛选
const handleFilter = () => {
  pagination.page = 1
  fetchList()
}

// 分页
const handlePageChange = () => {
  fetchList()
}

const handleSizeChange = () => {
  pagination.page = 1
  fetchList()
}

// 添加设备
const handleAdd = () => {
  dialogTitle.value = '添加设备'
  isEdit.value = false
  Object.assign(form, {
    deviceId: '',
    deviceName: '',
    ipAddress: ''
  })
  dialogVisible.value = true
}

// 编辑设备
const handleEdit = (row) => {
  dialogTitle.value = '编辑设备'
  isEdit.value = true
  Object.assign(form, {
    deviceId: row.deviceId,
    deviceName: row.deviceName,
    ipAddress: row.ipAddress || ''
  })
  dialogVisible.value = true
}

// 查看详情
const handleView = (row) => {
  router.push(`/devices/${row.deviceId}`)
}

// 删除设备
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除设备 ${row.deviceName} 吗？`,
      '提示',
      {
        type: 'warning'
      }
    )
    
    await deleteDevice(row.deviceId)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    if (isEdit.value) {
      await updateDevice(form.deviceId, form)
      ElMessage.success('更新成功')
    } else {
      await createDevice(form)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 定时刷新
let timer = null
onMounted(() => {
  fetchData()
  // 每10秒刷新一次
  timer = setInterval(fetchData, 10000)
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.device-list-page {
  height: 100%;
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  width: 70px;
  height: 70px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.online {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.offline {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.rate {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #999;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.device-list-card {
  margin-bottom: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.toolbar-left,
.toolbar-right {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

